<?php

namespace app\mobile\controller;

use Alipay\Alipayobj;
use app\common\controller\Platurl;
use app\common\model\CardCzgive;
use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardMember;
use app\common\model\CardMemberAli;
use app\common\model\CardOrder;
use app\common\model\CardShareRule;
use app\common\model\CardShareUser;
use app\common\model\CardStore;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserGetAli;
use app\common\model\CardUserUpdate;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardmarketest extends Mobilebase
{
    //卡券分享
    /*
     * 参数
     * $card_id /  授权获取openid
     */
    public function cardshare(Request $request)
    {


        $this->_init();

        $arr = $request->param();
        $card_id = $arr['card_id'];
        $appid = $this->getappid($card_id);
        $map['card_id'] = $card_id;
        $map['openid'] = Session::get($appid.'_openid');
        $map['have'] = 1;

        $CardUserGet = new CardUserGet();
        $userinfo = $CardUserGet->where($map)->field('code')->find();

        //不存在符合条件的则跳转到投放页面
        if (empty($userinfo)) {
            $data['card_id'] = $card_id;
            $data['openid'] = Session::get($appid.'_openid');
            $this->redirect('Carduser/addcard', $data);
        //存在则分享
        } else {
            $CardShareRule = new CardShareRule();
            $CardShareUser = new CardShareUser();
            $info = $CardShareRule->where('card_id',$card_id)->find();
            if ($info) {
                $infouser =  $CardShareUser->where(['card_id'=>$card_id,'openid'=>$map['openid']])->find();
                $CardMember = new CardMember();
                $cardinfo = $CardMember->where(['card_id'=>$arr['card_id']])->field('logo_url,activate,title')->find();
                //不存在记录则创建
                if (!isset($infouser)) {
                    $outerstr = ['openid' => Session::get($appid . '_openid'), 'share' => $info['id']];      //领卡来源
                    $card = $this->get_top_mid($card_id);                        //卡券mid/top_mid
                    //数据
                    $datas['openid'] = Session::get($appid . '_openid');
                    $datas['card_id'] = $card_id;
                    $datas['top_mid'] = $card['top_mid'];
                    $datas['rule_name'] = $info['title'];
                    $datas['code'] = $userinfo['code'];
                    $datas['rule_id'] = $info['id'];
                    $datas['rule_type'] = $info['rule_type'];
                    $datas['mid'] = $card['mid'];
                    $datas['outerstr'] = implode('_', $outerstr);
                    $datas['qrcode_url'] = $this->qrcodes($card_id, $datas['outerstr'],$card['activate']);
                    $datas['biz_url'] = $datas['qrcode_url'];
                    $datas['card_type'] = $this->getcardtype($card_id);
                    $datas['create_time'] = time();
                    $datas['url_type'] = $cardinfo['activate'];
                    $CardShareUser->allowField(true)->save($datas);
                    $infouser = $CardShareUser->where(['card_id' => $card_id, 'openid' => $map['openid']])->find();
                }
                $share['wxjssdk'] = $this->getsharejssdk($card_id);
                $share['data']['title'] = $info['title'];
                //
//                var_dump($infouser['id']);
                $Platurl = new Platurl();
                $agent_url = $Platurl->getagenturl('card_id',$arr['card_id']);
                //END

                $logo_url = $cardinfo['logo_url'];
//
                $info['logo_url'] = $logo_url;
                $share['data']['title'] = $info['title'];
                $share['data']['desc'] = $info['description'];
                $share['data']['link'] = $agent_url.'/mobile.php/cardmarke/shareget/rule_id/' . $infouser['id'] . '/card_id/' . $card_id;
                $share['data']['imgUrl'] = $logo_url;
                $share['wxjssdk'] = json_encode($share['wxjssdk']);
                $share['data'] = json_encode($share['data'], JSON_UNESCAPED_UNICODE);
                $this->assign('card',$cardinfo);
                $this->assign('user', $infouser);
                $this->assign('share', $share);
                $this->assign('info', $info);       //user
                return $this->fetch();
            }else{
                $this->setsharecard($arr);
                $this->cardshare();
            }
        }
    }

    //设置默认分享规则
    public function setsharecard($arr){
        $CardMember = new CardMember();
        $cardinfo = $CardMember->where(['card_id'=>$arr['card_id']])->field('title')->find();
        $CardShareRule = new CardShareRule();
        $data['card_id'] = $arr['card_id'];
        $data['card_type'] = 'MEMBER_CARD';
        $data['title'] = $cardinfo['title'];
        $data['rule_type'] = 'SHARE';
        $data['create_time'] = time();
        $CardShareRule->allowField(true)->save($data);

    }

    //获取分享二维码
    public function get_shareqrcode(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $appid = $this->getappid($arr['card_id']);
            $CardShareUser = new CardShareUser();
            $qrcode_url =  $CardShareUser->where(['card_id'=>$arr['card_id'],'openid'=>$arr['openid']])->value('qrcode_url');
            if (!$qrcode_url) {
                $outerstr = ['openid' => Session::get('card_openid'), 'share' => $arr['info_id']];      //领卡来源
                $card = $this->get_top_mid($arr['card_id']);                        //卡券mid/top_mid
                //数据
                $datas['outerstr'] = implode('_', $outerstr);
                $datas['qrcode_url'] = $this->getqrcode($arr['card_id'], $datas['outerstr']);
                $map['card_id'] = $arr['card_id'];
                $map['openid'] = $arr['openid'];
                $res = $CardShareUser->allowField(true)->save($datas,$map);
                if ($res){
                    $data['codes'] = 0;
                    $data['msg'] = 'success';
                    $data['qrcode_url'] = $datas['qrcode_url'];
                }else{
                    $data['codes'] = 9001;
                    $data['msg'] = 'error';
                    $data['qrcode_url'] = $datas['qrcode_url'];
                }
            }else{
                $data['codes'] = 0;
                $data['msg'] = 'success';
                $data['qrcode_url'] = $qrcode_url;
            }
            return json($data);
        }
    }

    //分享领取
    /*
     * $rule_id \ $card_id
     */
    public function shareget(){
        $this->_init();
        $arr = request()->param();
        $CardShareUser = new CardShareUser();
        $CardShareRule = new CardShareRule();
        $CardMember = new CardMember();
        $infouser = $CardShareUser->where('id',$arr['rule_id'])->find();
        if (isset($infouser['rule_id'])) {
            $info = $CardShareRule->where(['id' => $infouser['rule_id']])->find();
            if ($info) {
                $CardShareUser->where('id', $infouser['rule_id'])->setInc('view');
                $card = $CardMember->where(['card_id' => $arr['card_id']])->field('logo_url,title,prerogative,brand_name,base_info,bonus_rule,pic_url,color')->find();
                $card['base_info'] = json_decode($card['base_info'], true);
                $card['bonus_rule'] = json_decode($card['bonus_rule'], true);
                $info['rule_user'] = $infouser['id'];
                $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
                $share['wxjssdk'] = json_encode($share['wxjssdk']);
                $this->assign('share', $share);
                $this->assign('card', $card);
                $this->assign('info', $info);       //user
                return $this->fetch();
            }else{
                echo "请设置分享规则后使用";
                return $this->fetch('off');
            }
        }
    }

    //获取top_mid
    /*
     * 参数
     * $card_id
     */
    private function get_top_mid($card_id){
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $card = $CardMember->where('card_id',$card_id)->field('mid,top_mid,id,activate')->find();
        if ($card){
            return $card;
        }else{
            $card = $CardGeneral->where('card_id',$card_id)->field('mid,top_mid,id')->find();
            return $card;
        }
    }

    //分享jssdk
    /*
     * 参数
     * $card_id
     */
    public function getsharejssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }

    //卡券类型
    /*
     * 参数
     * $card_id
     */
    private function getcardtype($card_id){
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $card_type = $CardMember->where('card_id',$card_id)->value('card_type');
        if ($card_type){
            return $card_type;
        }else{
            $card_type = $CardGeneral->where('card_id',$card_id)->value('card_type');
            return $card_type;
        }
    }

    //获取公众号二维码
    public function getwxqrcode(){
        if (Request()->isAjax()){
            $arr = request()->param();
            $Cardmember = new CardMember();
            $Momerchant = new Momerchant();
            $WxOpen = new WxOpen();
            $map['id'] = $Cardmember->where(['card_id'=>$arr['cardid']])->value('top_mid');
//        var_dump($Cardmember->getLastSql());
            $wx_open_id = $Momerchant->where($map)->value('wx_open_id');
//        var_dump($Momerchant->getLastSql());
            $qrcode = $WxOpen->where(['id' => $wx_open_id])->value('qrcode_url');
//        var_dump($WxOpen->getLastSql());
            if ($qrcode){
                $data['code'] = 0;
                $data['message'] = 0;
                $data['date'] = $qrcode;
            }else{
                $data['code'] = 9001;
                $data['message'] = 0;
                $data['date'] = $arr;
            }
            return json($data);
        }
    }


    //商户免费券
    public function freecards(){
        $this->_init();
        $arr = request()->param();
        $appid = $this->getappid($arr['card_id']);
        if (!isset($arr['openid'])){
            $arr['openid'] = Session::get($appid.'_openid');
        }
        $this->assign('card',$arr);
        return $this->fetch();
    }

    //获取商户优惠券
    public function getfreecards(){
        $param = request()->post();
        $CardGeneral = new CardGeneral();
        $top_mid = $this->gettopmid($param['card_id']);
        $map['top_mid'] = $top_mid;
        $map['is_pay'] = 0;
        $map['is_cgive'] = 0;
        $map['is_mach'] = 1;
        $map['end_timestamp'] = ['GT',time()];
        $cardlists = $CardGeneral->where($map)->paginate(5);
        $cardcount = $CardGeneral->where($map)->count('id');
        $page_num = ceil($cardcount / 5);
        if ($cardlists) {
            if($page_num > (int)$param['page'] || $page_num == (int)$param['page']) {
                $cardlist = [];
                $i = 0;
                foreach ($cardlists as $k => $v) {
                    $cardget = getcardgetsume($v['card_id']);
                    $userget = getcardgetuser($v['card_id'], $param['openid']);
                    if ($cardget > $userget) {
                        $cardlist[$i]['get_num'] = $cardget - $userget;
                    } else {
                        $cardlist[$i]['get_num'] = 0;
                    }
                    $cardlist[$i]['card_id'] = $v['card_id'];
                    $cardlist[$i]['card_type'] = getcardtype($v['card_type']);
                    $cardlist[$i]['card_logo'] = $v['logo_url'];
                    $cardlist[$i]['card_title'] = $v['title'];
                    $cardlist[$i]['brand_name'] = $v['brand_name'];
                    $cardlist[$i]['end_times'] = filtergqcards($v['card_id']);
                    $i = $i + 1;

                }
                if ($cardlist) {
                    $data['code'] = 0;
                    $data['message'] = 'SUCCESS';
                    $data['data'] = $cardlist;
                    $data['count'] = count($cardlists);
                    $data['page'] = $param['page'];
                    $data['page_num'] = ceil($cardcount / 5);
                } else {
                    $data['code'] = 0;
                    $data['data'] = '';
                    $data['message'] = 'error';
                    $data['count'] = $cardcount;
                    $data['page_num'] = ceil($cardcount / 5);
                    $data['page'] = $param['page'];
                }
            }else{
                $data['code'] = 9002;
                $data['data'] = '';
                $data['message'] = 'error';
                $data['page_num'] = $page_num;
                $data['count'] = $cardcount;
                $data['page'] = $param['page'];
            }
        }else{
            $data['code'] = 9002;
            $data['data'] = '';
            $data['message'] = 'error';
            $data['page_num'] = $page_num;
            $data['count'] = $cardcount;
            $data['page'] = $param['page'];
        }
        return json($data);
    }

    public function getshopcardid($card_id){
        $map['card_id'] = $card_id;
        $map['statu'] = ['neq',2];
        $CardGoods = new CardMember();
        $list = $CardGoods->where($map)->order('id asc')->select();
    }


    //获取分享人
    /*
     * 参数 分享人id
     * $rule_id
     */
    private function getsharerule($arr){
        $CardShareUser = new CardShareUser();
        $CardShareRule = new CardShareRule();
        $info['user'] = $CardShareUser->where('id',$arr['rule_id'])->find();
        return $info;
    }

    //发放卡券
    /*
     *  分享人id
     */
    public function addcard()
    {
        $arr = request()->param();
        if (isset($arr['rule_id'])) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $sharerule = $this->getsharerule($arr);
            $options = $this->options($sharerule['user']['card_id']);
            //发放
            $arrs['card_id'] = $sharerule['user']['card_id'];
            $arrs['outerstr'] = $sharerule['user']['outerstr'];
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $sdk = $weObj->getJsSign($url);
            $jssdk['debug'] = true;
            $jssdk['api_ticket'] = $sdk['ticket'];
            $jssdk['url'] = $sdk['url'];
            $jssdk['appId'] = $sdk['appId'];
            $jssdk['timestamp'] = $sdk['timestamp'];
            $jssdk['nonceStr'] = $sdk['nonceStr'];
            $jssdk['signature'] = $sdk['signature'];
            $jssdk['jsApiList'] = ['penCard','addCard'];
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }

    //Ajax打开领取
    public function getaddcard(){
        if (Request()->isAjax()){
            $arr = request()->post();
//            return json($arr);
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = Session::get('card_openid');
            $arrs['share'] = $arr['share'];
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->get_card_JsSign($url);
            //输出内容
            $card['jssdk']['debug'] = true;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['penCard','addCard'];
            $card['card'] = $this->put($arrs);
            return json($card);
        }
    }

    //投放卡
    /*
     * 参数
     * $card_id / $outerstr
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = $arr['outerstr'];
        $res['card_id'] = $arr['card_id'];
        $res['addcard'] = $weObj->wxAddCardShare($arr['card_id'],$outer_str, $noncestr);
        return $res;
    }

    //获取二维码循环 为解决第一次执行accesstoken miss 问题
    /*
     * 参数
     * $card_id $outerstr
     */
    private function qrcodes($card_id, $outerstr,$actvtype=''){
        if ($actvtype == 1) {
            $Cardextend = new Cardextend();
            $data['card_id'] = $card_id;
            $data['outer_str'] = $outerstr;
            $res = $Cardextend->getcardusbizurl($data);
//        exit();
            return $res;
        }else{
            $this->getqrcode($card_id, $outerstr);
        }
    }



    //获取二维码
    /*
     * 参数
     * $card_id $outerstr
     */
    private function getqrcode($card_id, $outerstr){
        //发送数据
        $data = [
            "action_name"=>"QR_CARD",
            "action_info"=> [
                "card"=> [
                    "card_id" => $card_id,
                    "outer_str" => $outerstr
                ],
            ]
        ];
        //微信
        $options = $this->options($card_id);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->cardQrcode($data);
        if($res['errcode'] == 0){
            $qrcode_url = $res['show_qrcode_url'];
            return $qrcode_url;
        }else{
            $this->qrcodes($card_id, $outerstr);
        }
    }


    //更新积分数据
    /*
     * $arr['card_id'] / $arr['code'] / $arr['price'] / $arr['name'] / $data['add_bonus'] / $data['outerstr']
     *
     */
    public function varybonus($arr){
        if ($arr['add_bonus'] > 0) {
            $data = array(
                'card_id' => $arr['card_id'],
                'code' => $arr['code'],
                'add_bonus' => $arr['add_bonus'],
                'record_bonus' => $arr['name'],
                "notify_optional" => array(
                    "is_notify_bonus" => true,
                    "is_notify_balance" => true,
                    "is_notify_custom_field1" => true
                )
            );
            $options = $this->options($arr['card_id']);
            $weObj = new Wxobjopen($options);
            $res = $weObj->updateUserInfo($data);                   //发送通知
            if ($res['errcode'] == 0) {
                $bonus['mid'] = $this->getmid($arr['card_id']);
                $bonus['add_bonus'] = abs($data['add_bonus']);
                $bonus['record_bonus'] = $arr['name'];
                $bonus['openid'] = $arr['openid'];
                $bonus['card_id'] = $arr['card_id'];
                $bonus['con_username'] = 'RANKGIFT';                  //类型
                $bonus['type'] = 1;                  //类型
                $bonus['hx_fs'] = 7;                 //来源
                $bonus['reason'] = 5;                //原因
                $bonus['cate'] = 2;                  //类别
                $bonus['code'] = $arr['code'];
                $bonus['create_time'] = time();
                $bonus['outerstr'] = $arr['outerstr'];
                $bonus['tplmesg_info'] = json_encode($res);
                $CardUserUpdate = new CardUserUpdate();
                $CardUserGet = new CardUserGet();
                $CardUserUpdate->allowField(true)->save($bonus);                    //保存记录
                $map['openid'] = $bonus['openid'];
                $map['card_id'] = $bonus['card_id'];
                $CardUserGet->where($map)->setField('bonus', $res['result_bonus']);     //更新记录
                return '0';
            } else {
                return '1';
            }
        }else{
            return '0';
        }
    }

    //更新余额数据
    /*
     * $arr['card_id'] / $arr['code'] / $arr['balance'] / $arr['name'] / $data['add_balance'] / $data['type'] / $data['outerstr'] / $data['openid']
     *
     */
    public function varybanlance($arr){
        if ($arr['balance'] > 0) {
            $data['card_id'] = $arr['card_id'];
            $data['balance'] = $arr['balance'];
            $data['add_balance'] = $arr['add_balance'];
            $data['balance'] = $arr['balance'];
            $data['type'] = $arr['type'];
            $data['openid'] = $arr['openid'];
            $wxMsg = new Wxtplmesg();
            $res = $wxMsg->balancesendmesg($data);                  //发送通知
//            if ($res['errcode'] == 0) {
                $bonus['mid'] = $this->getmid($arr['card_id']);
                $bonus['add_balance'] = abs($data['add_balance']);
                $bonus['record_bonus'] = $arr['name'];
                $bonus['openid'] = $arr['openid'];
                $bonus['card_id'] = $arr['card_id'];
                $bonus['code'] = $arr['code'];
                $bonus['con_username'] = 'RANKGIFT';                  //类型
                $bonus['type'] = 1;                  //类型
                $bonus['hx_fs'] = 7;                 //来源
                $bonus['reason'] = 5;                //原因
                $bonus['cate'] = 1;                  //类别
                $bonus['create_time'] = time();
                $bonus['outerstr'] = $arr['outerstr'];
                $bonus['tplmesg_info'] = json_encode($res);
                $CardUserUpdate = new CardUserUpdate();
                $CardUserGet = new CardUserGet();
                $CardUserUpdate->allowField(true)->save($bonus);            //保存记录
                $map['openid'] = $bonus['openid'];
                $map['card_id'] = $bonus['card_id'];
                $CardUserGet->where($map)->setInc('balance', $arr['add_balance']);      //更新数据
                return '0';
//            } else {
//                return "1";
//
//            }
        }else{
            return '0';
        }
    }


    /* 获取创建该卡券的门店id
    *
    * $card_id
    * $card_id
    *
    */
//    private function getmid($card_id)
//    {
//        $CardMember = new CardMember();
//        $CardGeneral = new CardGeneral();
//        $mid = $CardMember->where(['card_id' => $card_id])->value('mid');
//        if (empty($mid)) {
//            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
//            return $mid;
//        } else {
//            return $mid;
//        }
//    }

    //支付宝分享
    public function cardshareali(){
//        $alibase = new Mobileali();
//        $alibase->_init();
        $arr = request()->param();
        $map['mid'] = $arr['mid'];
//        $map['user_id'] = Session::get('card_user_id');
        $map['user_id'] = '2088702437218941';
        $map['card_type'] = 'OUT_MEMBER_CARD';
        $map['have'] = 1;
        $CardUserGet = new CardUserGetAli();
        $userinfo = $CardUserGet->where($map)->find();

        //不存在符合条件的则跳转到投放页面
        if ($userinfo) {

            $CardShareUser = new CardShareUser();
            $infouser =  $CardShareUser->where(['template_id'=>$userinfo['template_id'],'user_id'=>$map['user_id']])->find();
            $card = $this->get_card_info($userinfo['template_id']);                        //卡券mid/top_mid getcard_url
            //不存在记录则创建
            if (!$infouser) {
                //数据
                $datas['user_id'] = $map['user_id'];
                $datas['template_id'] = $userinfo['template_id'];
                $datas['top_mid'] = $card['top_mid'];
                $datas['code'] = $userinfo['code'];
                $datas['mid'] = $card['mid'];
                $datas['share_url_pre'] = request()->domain() .'/mobile.php/cardaliget/cardget'.'/share_uid/'.$userinfo['user_id'];
                $geturl = $this->getshareurl($datas);
                if ($geturl['code'] = 10000){
                    $datas['share_url'] = $geturl['getcard_url'];
                    $datas['card_type'] = $userinfo['card_type'];
                    $datas['create_time'] = time();
                    $CardShareUser->allowField(true)->save($datas);
                }
            }
            $share['data']['link'] = request()->domain() .'/mobile.php/cardmarke/sharegetali/template_id/'.$userinfo['template_id'].'/share_uid/'.$userinfo['user_id'];
//            $share['data'] = json_encode($share['data'],JSON_UNESCAPED_UNICODE);
//            var_dump($share);
            $this->assign('card',$card);
            $this->assign('info',$infouser);
//            var_dump(json_encode($infouser));
            $this->assign('share',$share);
            return $this->fetch();

        } else {
            $data['mid'] = $arr['mid'];
            $data['user_id'] = Session::get('card_user_id');
            $this->redirect('Carduserali/addcard', $data);
            //存在则分享

        }
    }

    //领取
    public function sharegetali(){
        $arr = request()->param();
        $CardMemberAli = new CardMemberAli();
        $card = $CardMemberAli->where(['template_id'=>$arr['template_id']])->find();
        $map['user_id'] = $arr['share_uid'];
        $map['template_id'] = $arr['template_id'];
        $CardShareUser = new CardShareUser();
        $shareinfo = $CardShareUser->where($map)->find();
        if ($shareinfo){
            $this->assign('info',$shareinfo);
            $this->assign('card',$card);
            return $this->fetch();
        }else{
            $data['template_id'] = $arr['template_id'];
            $data['user_id'] = $arr['user_id'];
            $this->redirect('Carduserali/addcard', $data);
        }
    }

    //获取分享链接
    public function getshareurl($arr){

        $datas['merchid'] = $arr['mid'];
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateurl.apply";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'template_id' => $arr['template_id'],
            "callback" => $arr['share_url_pre'],
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        if ($content['alipay_marketing_card_activateurl_apply_response']['code'] == 10000) {
            $params['getcard_url'] = urldecode($content['alipay_marketing_card_activateurl_apply_response']['apply_card_url']);
            $params['code'] = $content['alipay_marketing_card_activateurl_apply_response']['code'];
        } else {
            $params['code'] = $content['alipay_marketing_card_activateurl_apply_response']['code'];
            $params['data']['msg'] = $content['alipay_marketing_card_activateurl_apply_response']['msg'];;
        }
        return $params;
    }

    private function get_card_info($template_id){
        $CardMemberAli = new CardMemberAli();
        $merchid = $CardMemberAli->where(array('template_id'=>$template_id))->field('mid,top_mid,bg_url_abs,template_id,logo_url_abs,card_show_name')->find();
        return $merchid;
    }

    //获取mid 通过tempalte_id
    private function get_mid($template_id){
        //获取mid
        $CardMemberAli = new CardMemberAli();
        $merchid = $CardMemberAli->where(array('template_id'=>$template_id))->value('mid');
        return $merchid;
    }

}
